﻿using Game.Map.Internal;

namespace Game.Map.Extensions.Internal
{
    class VisibleUpdater
    {
        readonly IGameMapView _View;

        public VisibleUpdater(IGameMapView view)
        {
            _View = view;
            foreach (MapField field in view.Fields)
            {
                field.VehicleX().VehicleAssigned += (source, args) => UpdateVisible(args.MapField);
                UpdateVisible(field);
            }
            _View.AfterResetVisible += (source, args) => UpdateVisible();
        }

        void UpdateVisible()
        {
            foreach (MapField field in _View.Fields)
            {
                UpdateVisible(field);
            }
        }

        void UpdateVisible(
            IMapField field)
        {
            if (field.VehicleX().Vehicle == null)
            {
                return;
            }

            if (field.VehicleX().Vehicle.Owner != _View.Owner)
            {
                return;
            }

            var collection = MapUtil.GetArea(
                _View, field.Point, field.VehicleX().Vehicle.Movement.Max);
            foreach (var cursor in collection)
            {
                var f = _View.Collection[cursor.Point];
                f.IsVisible = true;
            }
            {
                var f = _View.Collection[field.Point];
                f.IsVisible = true;
            }
        }
    }
}
